package minimumOperationsToReduceXToZero_1658;

public class Solution {

    public static int minOperations(int[] nums, int x) {
        long total = 0;
        for (int num : nums) {
            total += num;
        }
        if (total < x) {
            return -1;
        }
        if (total == x) {
            return nums.length;
        }
        long target = total - x;
        int temp = nums[0];
        int maxLength = -1;
        int left = 0, right = 0;

        while (right != nums.length) {
            if (temp == target) {
                maxLength = Math.max(maxLength, right - left + 1);
                temp += nums[right++];
            } else if (temp < target) {
                right++;
                if (right == nums.length) {
                    break;
                }
                temp += nums[right];
            } else {
                temp -= nums[left++];
            }
        }

        return maxLength > 0 ? nums.length - maxLength : -1;
    }


    public static void main(String[] args) {
        System.out.println(minOperations(new int[]{1, 1, 4, 2, 3}, 5));
        System.out.println(minOperations(new int[]{5, 6, 7, 8, 9}, 4));
        System.out.println(minOperations(new int[]{3, 2, 20, 1, 1, 3}, 10));
    }
}
